package com.unisiot.zk_flutter_bluetooth_print;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.nfc.Tag;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.util.Base64;

import androidx.annotation.NonNull;

import org.w3c.dom.Text;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import zpSDK.zpSDK.GZIPFrame;
import zpSDK.zpSDK.zpBluetoothPrinter;

/**
 *
 * ZkFlutterBluetoothPrintPlugin
 *
 * */
public class ZkFlutterBluetoothPrintPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    private Context applicationContext;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPlugin.FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "zk_flutter_bluetooth_print");
        channel.setMethodCallHandler(this);
        applicationContext =  flutterPluginBinding.getApplicationContext();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if ("connect".equals(call.method)) {
            String bdAddress = call.argument("BDAddress");

            Log.d("zk_flutter_bluetooth_print","bd addres =="+bdAddress);

            boolean connect = false;
            try {
                zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(applicationContext);
                connect = zpSDK.connect(bdAddress);
            } catch (Exception e) {
                result.success("{\"code\":\""+ connect + "\",\"desc\":\"bdAddress:" + bdAddress + "的蓝牙设备连接失败\"}");
                Log.d("HPRTSDKSample", e.getMessage().toString());
            }
            boolean connectStatus = connect;
            if(connectStatus){
                Log.d("zk_flutter_bluetooth_print","打印机连接上了");
                result.success("{\"code\":\"0\",\"desc\":\"bdAddress:" + bdAddress + "的蓝牙设备连接成功\"}");
            } else {
                Log.d("zk_flutter_bluetooth_print","打印机连接失败--" + connectStatus);
                result.success("{\"code\":\"-1\",\"desc\":\"bdAddress:" + bdAddress + "的蓝牙设备连接失败\"}");
            }
        } else if ("printImage".equals(call.method)) {
            String url = call.argument("url");
            String width = call.argument("width");
            String height = call.argument("height");
            OkHttpClient client = new OkHttpClient();

            if (TextUtils.isEmpty(url)){
                result.success("{\"code\":\"-1\",\"desc\":\"url 为空，请确认\"}");
            }
            Log.d("zk_flutter_bluetooth_print","==url==="+url);
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    result.success("{\"code\":\"-2\",\"desc\":\"下载图片失败，请确认\"}");
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (null == response.body()){
                        result.success("{\"code\":\"-2\",\"desc\":\"图片数据流为空，请确认\"}");
                        return;
                    }
                    zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(applicationContext);
                    InputStream bitmapStream = response.body().byteStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(bitmapStream);

                    int newWidth = width == null ? 555 : Integer.parseInt(width);
                    int newHeight = height == null ? 785 : Integer.parseInt(height);
                    Bitmap img =Bitmap.createScaledBitmap(bitmap,newWidth,newHeight,false);

                    Log.d("zk_flutter_bluetooth_print","打印准备了--width:" + newWidth + "---height:" + newHeight);
                    zpSDK.pageSetup(574, 0);
                    byte[] b= GZIPFrame.Draw_Page_Bitmap_(img);
                    zpSDK.Write(b);

                    zpSDK.print(0, 0);
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            result.success("{\"code\":\"0\",\"desc\":\"打印成功\"}");
                        }
                    },2000);
                }
            });

        } else if ("printBase64Image".equals(call.method)) {
            String base64 = call.argument("base64");
            String width = call.argument("width");
            String height = call.argument("height");

            if (TextUtils.isEmpty(base64)){
                result.success("{\"code\":\"-1\",\"desc\":\"base64 为空，请确认\"}");
            }

            try {
                Bitmap bitmap = null;
                bitmap = base64ToPicture(base64);
                int newWidth = width == null ? 555 : Integer.parseInt(width);
                int newHeight = height == null ? 785 : Integer.parseInt(height);
                Bitmap img = Bitmap.createScaledBitmap(bitmap,newWidth,newHeight,false);

                zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(applicationContext);
                Log.d("zk_flutter_bluetooth_print","打印准备了--width:" + newWidth + "---height:" + newHeight);
                zpSDK.pageSetup(574, 0);
                byte[] b= GZIPFrame.Draw_Page_Bitmap_(img);
                zpSDK.Write(b);

                zpSDK.print(0, 0);
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        result.success("{\"code\":\"0\",\"desc\":\"打印成功\"}");
                    }
                },2000);
            } catch (Exception e) {
                result.success("{\"code\":\"-1\",\"desc\":\"base64 为空，请确认\"}");
            }


        } else if ("disConnect".equals(call.method)) {
            try {
                zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(applicationContext);
                zpSDK.disconnect();
                result.success("{\"code\":\"0\",\"desc\":\"断开连接成功\"}");
                Log.d("HPRTSDKSample", "断开连接成功");
            } catch (Exception e) {
                result.success("{\"code\":\"-1\",\"desc\":\""+ e.getMessage().toString() +"\"}");
                Log.d("HPRTSDKSample", e.getMessage().toString());
            }
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    /**
     * 将图片base64数据转化为bitmap
     *
     * @param imgBase64
     * @return
     * @throws Exception
     */
    public static Bitmap base64ToPicture(String imgBase64) throws Exception {
        //处理头部
        if (imgBase64.contains(",")) {
            imgBase64 = imgBase64.split(",")[1];
        }
        //解码开始
        byte[] decode = Base64.decode(imgBase64, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        return bitmap;
    }

}
